﻿using AutoMapper;
using AutoMapper.QueryableExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Cms.Core.Infrastructure.Extension
{
    /// <summary>
    /// AutoMapper扩展方法
    /// </summary>
    public static class AutoMapperExtensions
    {


        /// <summary>
        /// 类型映射
        /// </summary>
        /// <typeparam name="TSource">源对象</typeparam>
        /// <typeparam name="TTarget">目标对象</typeparam>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static TTarget MapperTo<TSource, TTarget>(this TSource source, TTarget target) where TSource : class
            where TTarget:class
        {
            source.NotNull(nameof(source));
            target.NotNull(nameof(target));
      
            return Mapper.Map(source, target);

        }




        /// <summary>
        /// 对象对对象
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="self"></param>
        /// <returns></returns>
        public static TResult MapperTo<TResult>(this object self) where TResult:class
        {

            if (self == null)
            {
                return default(TResult);
            }


            return (TResult)Mapper.Map<TResult>(self);
        }

        /// <summary>
        /// 转成dto
        /// </summary>
        /// <typeparam name="TSource">数据源</typeparam>
        /// <typeparam name="TDestination">目标</typeparam>
        /// <param name="source">数据源</param>
        /// <param name="membersToExpand">过滤</param>
        /// <returns></returns>

        public static IQueryable<TDestination> ToOutput<TSource, TDestination>(this IQueryable<TSource> source, params Expression<Func<TDestination, object>>[] membersToExpand)
        {

            if (source.IsNull())
            {
                return default(IQueryable<TDestination>);
            }

            return source.ProjectTo<TDestination>(membersToExpand);

        }
    }
}
